package action;

import beans.Account;
import dao.CheckAccount;
import helper.ReadConfig;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        ReadConfig readCon = new ReadConfig();
        Connection con = readCon.getDBConnection();
        Account account = new Account();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String msg = "";
        account.setUser_name(username);
        account.setPass_word(password);
        CheckAccount checkAcc = new CheckAccount();
        account = checkAcc.checkLogin(account, con);
        if (account.getFull_name() != null && !account.getFull_name().equals("")) {
            session.setAttribute("acc", account);
            session.setAttribute("acc_id", account.getAcc_id());
            session.setAttribute("username", account.getUser_name());
            session.setAttribute("password", account.getPass_word());
            session.setAttribute("full_name", account.getFull_name());
            session.setAttribute("roll", account.getRoll());
            session.setMaxInactiveInterval(3600);

            if (account.getRoll().equals("admin")) {
                RequestDispatcher rq = request.getRequestDispatcher("index.jsp");
                rq.forward(request, response);
            }
            if (account.getRoll().equals("student")) {
                RequestDispatcher rq = request.getRequestDispatcher("student.jsp");
                rq.forward(request, response);
            }
            if (account.getRoll().equals("staff")) {
                RequestDispatcher rq = request.getRequestDispatcher("index.jsp");
                rq.forward(request, response);
            }
        } else {
            msg = "Username or Password incorrect !";
            request.setAttribute("msg", msg);
            RequestDispatcher rq = request.getRequestDispatcher("login.jsp");
            rq.forward(request, response);
        }
    }
}
